import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/safes_check_set_request.dart';
import 'package:elephant_fish/http/request/safes_fetch_request.dart';
import 'package:elephant_fish/http/request/safes_gold_request.dart';
import 'package:elephant_fish/http/request/safes_store_request.dart';
import 'package:elephant_fish/page/safes_alset_password_page.dart';
import 'package:elephant_fish/page/safes_set_password_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/util/string_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class SafeDepositBoxPage extends StatefulWidget {
  const SafeDepositBoxPage({Key key}) : super(key: key);

  @override
  _SafeDepositBoxPageState createState() => _SafeDepositBoxPageState();
}

class _SafeDepositBoxPageState extends State<SafeDepositBoxPage> {

  TextEditingController passwordController = TextEditingController();
  TextEditingController numberController = TextEditingController();
  int goldNum = 0;
  bool isChecked = false;
  bool isEmpty = true;
  String amount;
  double realNum = 0;
  String password ;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        actions: [
          InkWell(
            child:Align(
              alignment: Alignment.centerRight,
              child: Padding(
                padding: EdgeInsets.only(right: SizeUtil.px(30)),
                child: Text(
                  '设置二级密码',
                  style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
                ),
              ),
            ),
            onTap: (){
              isChecked? Navigator.of(context).push( MaterialPageRoute(builder: (context)=>SafesAlsetPasswordPage()))
                  :Navigator.of(context).push( MaterialPageRoute(builder: (context)=>SafesSetPasswordPage())).then((value) => {
                isSetPassword()
              });
            },
          )
        ],
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xfff3f3f3),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '保险箱',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: size.width,
              child: Align(
                alignment: Alignment.topCenter,
                child: Stack(
                  children: [
                    Align(
                      alignment: Alignment.topCenter,
                      child: Padding(
                        padding: EdgeInsets.only(top: SizeUtil.px(27)),
                        child:  Container(
                          width: SizeUtil.px(686),
                          height: SizeUtil.px(352.48),
                          decoration: BoxDecoration(
                            image:DecorationImage(image: AssetImage('assets/images/save_box_bj1.png')) ,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text( '可用金币', style: TextStyle(fontSize: SizeUtil.px(28),color: Color(0x80ffffff))),
                              SizedBox(height: SizeUtil.px(21),),
                              Text( goldNum.toString() , style: TextStyle(fontSize: SizeUtil.px(77),color: Color(0xffffffff))),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.topCenter,
                      child: Padding(
                        padding: EdgeInsets.only(top: SizeUtil.px(310)),
                        child:  Container(
                          width: size.width,
                          height: SizeUtil.px(157),
                          decoration: BoxDecoration(
                            image:DecorationImage(image: AssetImage('assets/images/safe_box_bj2.png')) ,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              width: SizeUtil.px(690),
              child: TextField(
                onChanged: (text){
                  amount = text;
                  realNum = (int.parse(amount) / 10000);
                  checkInput();
                },
                controller: numberController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  isCollapsed: true,
                  contentPadding: EdgeInsets.all(0),
                  hintText: '请输入金币数量',
                  hintStyle: TextStyle(
                      color: Color(0xffcccccc),
                      fontSize: SizeUtil.px(42)),
                ),
                style: TextStyle(
                    color: Color(0xffffffff),
                    fontSize: SizeUtil.px(42)),
              ),
            ),
            SizedBox(height: SizeUtil.px(42),),
            Divider(height: SizeUtil.px(1),color: Color(0xffeeeeee),indent: SizeUtil.px(30),endIndent: SizeUtil.px(30),),
            SizedBox(height: SizeUtil.px(26),),
            Text( '折合金额￥' + realNum.toString(), style: TextStyle(fontSize: SizeUtil.px(24),color: Color(0xff999999))),
            SizedBox(height: SizeUtil.px(284),),
            InkWell(
              child:  Container(
                width: SizeUtil.px(690),
                height: SizeUtil.px(92),
                decoration: BoxDecoration(
                  color: Color(0xffe62d6c),
                  borderRadius: BorderRadius.all(Radius.circular(SizeUtil.px(46))),
                ),
                child: Center(
                  child: Text( '存入', style: TextStyle(fontSize: SizeUtil.px(30),color: Color(0xffffffff))),
                ),
              ),
              onTap: (){
                if(!isEmpty){
                  safesStroe();
                }else{
                  TxUtils.showToast('存入金币数量必填', context);
                }
               
              },
            ),
            SizedBox(height: SizeUtil.px(26),),
            InkWell(
              child:  Container(
                width: SizeUtil.px(690),
                height: SizeUtil.px(92),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(SizeUtil.px(46))),
                  border: new Border.all(width: 1, color: Colors.white),
                ),
                child: Center(
                  child: Text( '取出', style: TextStyle(fontSize: SizeUtil.px(30),color: Color(0xffffffff))),
                ),
              ),
              onTap: (){
                if(isChecked){
                  if(!isEmpty){
                    _showPassword();
                  }else{
                    TxUtils.showToast('取出金币数量必填', context);
                  }
                }else{
                  TxUtils.showToast('请先设置二级密码', context);
                }

              },
            ),

          ],
        ),
      )
    );
  }

  void init() {
    ///初始金币数量
    getSafesGold();
    ///是否设置二级密码
    isSetPassword();
  }

  ///初始金币数量
  Future<void> getSafesGold() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = SafesGoldRequest();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){
      setState(() {
        goldNum = result['data']['num'];
      });
    }
  }

  void isSetPassword() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = SafesCheckSetReuqest();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){
      setState(() {
        isChecked = result['data']['is_check'];
      });
    }
  }

  ///存入
  Future<void> safesStroe() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = SafesStoreRequest();
    request.add('amount', amount).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){
      TxUtils.showToast(result['data'].toString(), context);
      numberController.clear();
      getSafesGold();
    }else{
      TxUtils.showToast(result['message'], context);
    }
  }

  void checkInput() {
    bool enable;
    if (isNotEmpty(amount) ) {
      enable = false;
    } else {
      enable = true;
    }
    setState(() {
      isEmpty = enable;
    });
  }

  void _showPassword() {
    final top = 12.0;
    final txBottom = 40.0;
    final txHeight = 100.0;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return StatefulBuilder(builder: (ctx2, state) {
          return Container(
            height: MediaQuery.of(ctx2).viewInsets.bottom +
                txHeight +
                top +
                txBottom,
            color: Colors.white,
            child: Stack(
              children: <Widget>[
                Positioned(
                    left: 12,
                    bottom: (MediaQuery.of(ctx2).viewInsets.bottom < 0)
                        ? 0
                        : MediaQuery.of(ctx2).viewInsets.bottom,
                    right: 0,
                    top: top,
                    child: Container(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: <Widget>[
                              Expanded(
                                  child: Container(
                                    padding: EdgeInsets.all(8),
                                    height: txHeight,
                                    color: Color(0xfff7f7f7),
                                    child: TextField(
                                      // scrollPadding: EdgeInsets.zero,
                                      controller: passwordController,
                                      autofocus: true,
                                      obscureText: true,
                                      keyboardType: TextInputType.number,
                                      maxLength: 6,
                                      style: TextStyle(
                                          fontSize: 15, color: Colors.black),
                                      decoration: InputDecoration(
                                          hintText: '请输入二级密码',
                                          counterText: '',
                                          hintStyle: TextStyle(color: Colors.black),
                                          contentPadding: EdgeInsets.zero,
                                          isDense: true,
                                          border: InputBorder.none),
                                    ),
                                  )),
                              InkWell(
                                child: Container(
                                  padding: EdgeInsets.only(left: 12, right: 12),
                                  child: Text("确定",
                                      style: TextStyle(
                                          fontSize: 15,
                                          color: Color(0xffe62d6c))),
                                ),
                                onTap: () {
                                  setState(() {
                                    password = passwordController.text;
                                    safesFetch();
                                  });
                                  Navigator.pop(context);
                                },
                              )
                            ],
                          ),
                        ],
                      ),
                    ))
              ],
            ),
          );
        });
      },
    );
  }

  Future<void> safesFetch() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = SafesFetchRequest();
    request.add('amount', amount).add('password', password).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){
      TxUtils.showToast(result['data'].toString(), context);
      numberController.clear();
      getSafesGold();
    }else{
      TxUtils.showToast(result['message'], context);
    }
  }
}
